﻿using CivitaiCLI.Utils;
using System;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace CivitaiCLI
{
    public delegate void ClipboardChangedEventHandler(object sender, ClipboardChangedEventArgs e);
    public class ClipboardChangedEventArgs : EventArgs
    {
        public string Text { get; protected set; }
        public ClipboardChangedEventArgs(string text)
        {
            Text = text;
        }
    }

    public class MessageOnlyWindow : Form
    {
        private const int WM_CLIPBOARDUPDATE = 0x031D;
        private static IntPtr HWND_MESSAGE = new IntPtr(-3);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool AddClipboardFormatListener(IntPtr hwnd);

        [DllImport("user32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        private static extern bool RemoveClipboardFormatListener(IntPtr hWnd);

        [DllImport("user32.dll", SetLastError = true)]
        private static extern IntPtr SetParent(IntPtr hWndChild, IntPtr hWndNewParent);

        public bool IgnoreNextCopy { get; set; } = false;

        public event ClipboardChangedEventHandler ClipboardChanged;
        private void OnClipboardChanged(string text)
        {
            ClipboardChanged?.BeginInvoke(this, new ClipboardChangedEventArgs(text), ClipboardChangedEndInvoke, null);
        }

        private void ClipboardChangedEndInvoke(IAsyncResult iar)
        {
            var ar = (System.Runtime.Remoting.Messaging.AsyncResult)iar;
            var invokedMethod = (ClipboardChangedEventHandler)ar.AsyncDelegate;

            try
            {
                invokedMethod.EndInvoke(iar);
            }
            catch {}
        }

        readonly bool attachedClipboardFormatListener;

        public MessageOnlyWindow()
        {
            SetParent(Handle, HWND_MESSAGE);
            attachedClipboardFormatListener = AddClipboardFormatListener(Handle);
        }

        protected override void WndProc(ref Message m)
        {
            if (m.Msg == WM_CLIPBOARDUPDATE)
            {
                if (IgnoreNextCopy)
                {
                    IgnoreNextCopy = false;
                }
                else
                {
                    var data = Clipboard.GetDataObject();
                    if (data?.GetDataPresent(DataFormats.Text) ?? false)
                    {
                        string text = data.GetData(DataFormats.Text) as string;
                        if (!string.IsNullOrEmpty(text))
                        {
                            OnClipboardChanged(text);
                        }
                    }
                    m.Result = IntPtr.Zero;
                }
            }

            base.WndProc(ref m);
        }

        protected override void OnFormClosing(FormClosingEventArgs e)
        {
            if (attachedClipboardFormatListener)
                RemoveClipboardFormatListener(Handle);

            base.OnFormClosing(e);
        }
    }
}